/*
 * Copyright (c) 2018-2999 深圳市阿毛科技有限公司 All rights reserved.
 *
 * https://www.lamyz.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.lam.mall.api.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.components.dict.DictUtil;
import com.lam.common.constant.MallStateConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.BusinessException;
import com.lam.common.exception.ParameterErrorException;
import com.lam.framework.operLog.annotation.Log;
import com.lam.mall.app.vo.MyOrderVo;
import com.lam.mall.app.vo.OrderItemVo;
import com.lam.mall.app.vo.OrderShopVo;
import com.lam.mall.app.vo.UserAddrVo;
import com.lam.mall.entity.Order;
import com.lam.mall.entity.OrderAddr;
import com.lam.mall.entity.OrderItem;
import com.lam.mall.entity.ShopDetail;
import com.lam.mall.enums.OrderStatus;
import com.lam.mall.service.OrderAddrService;
import com.lam.mall.service.OrderItemService;
import com.lam.mall.service.OrderService;
import com.lam.mall.service.ProdSkuService;
import com.lam.mall.service.ProductService;
import com.lam.mall.service.ShopDetailService;

import cn.hutool.core.bean.BeanUtil;

/**
 */
@RestController
@RequestMapping("/${frontPath}/myOrder")
@Log(title = "我的订单接口")
public class MyOrderApiController extends BaseController{

	@Autowired
    private OrderService orderService;

	@Autowired
    private OrderAddrService orderAddrService;
	@Autowired
    private ProductService productService;
	@Autowired
    private ProdSkuService prodSkuService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private OrderItemService orderItemService;


    /**
     * 订单详情信息接口
     * 根据订单号获取订单详情信息
     */
    @GetMapping("/orderDetail")
    @Log(oper = "订单详情信息")
    public Result orderDetail(@RequestParam(value = "orderNumber", required = true) String orderNumber) {

        String userId = TokenUtils.getLoginUserid();
        OrderShopVo orderShopVo = new OrderShopVo();
        Order order = orderService.selectSimpleByOrderNo(orderNumber);
        if (order == null) {
            throw new BusinessException("该订单不存在");
        }
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new BusinessException("你没有权限获取该订单信息");
        }

        ShopDetail shopDetail = shopDetailService.getByShopIdCache(order.getShopId());
        OrderAddr orderAddr = orderAddrService.selectById(order.getOrderAddrId());
        UserAddrVo userAddrVo = BeanUtil.copyProperties(orderAddr, UserAddrVo.class);
        List<OrderItem> orderItems = orderItemService.selectByOrderNoCache(orderNumber);
        List<OrderItemVo> orderItemVos = BeanUtil.copyToList(orderItems, OrderItemVo.class);

        orderShopVo.setShopId(shopDetail.getId());
        orderShopVo.setShopName(shopDetail.getShopName());
        orderShopVo.setActualTotal(order.getActualTotal());
        orderShopVo.setUserAddrVo(userAddrVo);
        orderShopVo.setOrderItemVos(orderItemVos);
        orderShopVo.setTotal(order.getTotal());
        orderShopVo.setTransfee(order.getDvyAmount());
        orderShopVo.setPayAmt(order.getPayAmt());
        orderShopVo.setReduceAmount(order.getReduceAmount());
        orderShopVo.setTotalNum(order.getProductNums());
        orderShopVo.setPayType(order.getPayType());
        orderShopVo.setCreateTime(order.getCreateTime());
        orderShopVo.setPayTime(order.getPayTime());
        orderShopVo.setRemarks(order.getRemarks());
        orderShopVo.setStatus(order.getStatus());

//        BigDecimal total = BigDecimal.ZERO;
//        Integer totalNum = 0;
//        for (OrderItemVo orderItem : orderShopVo.getOrderItemVos()) {
//            total = NumberUtil.add(total, orderItem.getProductTotalAmount());
//            totalNum += orderItem.getProdCount();
//        }
//        orderShopVo.setTotal(total);
//        orderShopVo.setTotalNum(totalNum);
        return Result.ok(DictUtil.convertJavaObject(orderShopVo));
    }


    /**
     * 订单列表接口
     * 根据订单状态获取订单列表信息，状态为0时获取所有订单
     */
    @GetMapping("/myOrder")
    @Log(oper = "订单列表信息")
    public Result myOrder(@RequestParam(value = "status") Integer status) {

    	startPage();
        String userId = TokenUtils.getLoginUserid();
        List<MyOrderVo> list = orderService.listPageByUserId(userId, status);
        return Result.ok(getTableData(list));
    }

    /**
     * 取消订单
     * 根据订单号取消订单
     */
    @PutMapping("/cancel/{orderNumber}")
    @Log(oper = "根据订单号取消订单" )
    public Result cancel(@PathVariable("orderNumber") String orderNumber) {
        String userId = TokenUtils.getLoginUserid();
        Order order = orderService.selectSimpleByOrderNo(orderNumber);
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new ParameterErrorException("你没有权限获取该订单信息");
        }
        if (!Objects.equals(order.getStatus(), OrderStatus.UNPAY.value())) {
            throw new ParameterErrorException("订单已支付，无法取消订单");
        }
        List<OrderItem> orderItems = orderItemService.selectByOrderNoCache(orderNumber);
        order.setOrderItems(orderItems);
        // 取消订单
        orderService.cancelOrder(order, MallStateConstant.ORDER_OPER_TYPE_BUYER);

        // 清除缓存
        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheById(orderItem.getProdId());
            prodSkuService.removeCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId());
        }
        return Result.ok();
    }


    /**
     * 确认收货
     */
    @PutMapping("/receipt/{orderNumber}")
    @Log(oper = "根据订单号确认收货")
    public Result receipt(@PathVariable("orderNumber") String orderNumber) {
        String userId = TokenUtils.getLoginUserid();
        Order order = orderService.selectSimpleByOrderNo(orderNumber);
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new BusinessException("你没有权限获取该订单信息");
        }
        if (!Objects.equals(order.getStatus(), OrderStatus.CONSIGNMENT.value())) {
            throw new BusinessException("订单未发货，无法确认收货");
        }
        List<OrderItem> orderItems = orderItemService.selectByOrderNo(orderNumber);
        order.setOrderItems(orderItems);
        // 确认收货
        orderService.confirmOrder(order, MallStateConstant.ORDER_OPER_TYPE_BUYER);

        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheById(orderItem.getProdId());
            prodSkuService.removeCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId());
        }
        return Result.ok();
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{orderNumber}")
    @Log(oper = "根据订单号删除订单")
    public Result delete(@PathVariable("orderNumber") String orderNumber) {
        String userId = TokenUtils.getLoginUserid();
        Order order = orderService.selectSimpleByOrderNo(orderNumber);
        if (order == null) {
            throw new BusinessException("该订单不存在");
        }
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new BusinessException("你没有权限获取该订单信息");
        }
        if (!Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value()) && !Objects.equals(order.getStatus(), OrderStatus.CLOSE.value()) ) {
            throw new BusinessException("订单未完成或未关闭，无法删除订单");
        }

        // 删除订单
        orderService.deleteOrders(Arrays.asList(order));
        return Result.ok("删除成功");
    }

    /**
     * 获取我的订单订单数量
     */
    @GetMapping("/orderCount")
    @Log(oper = "获取我的订单订单数量")
    public Result getOrderCount() {
        String userId = TokenUtils.getLoginUserid();
        return Result.ok(orderService.getOrderCount(userId));
    }


}
